from starchain import *
from astrofunctions import *
from astro_info import *
from zodiac_info import *
import gradio as gr
import sys
from logging.handlers import TimedRotatingFileHandler

def main(param):
    print(f"Received parameter: {param}")
    log_dir = "logs"
    os.makedirs(log_dir, exist_ok=True)  # 如果目录不存在就创建它
    # 日志文件基础名（不带日期）
    log_file_base = "star.log"
    log_file_name = os.path.join(log_dir, log_file_base)

    # 创建一个按天滚动的 FileHandler
    handler = TimedRotatingFileHandler(
        filename=log_file_name,
        when="midnight",  # 每天凌晨切换
        encoding="utf-8",
        delay=False
    )

    # 设置日志格式
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    # 获取 root logger，并添加 handler
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.addHandler(handler)

    # 清除历史函数
    def clear_history():
        return []

    css = '''
    footer {visibility: hidden}
    '''

    js_func = """
    function createGradioAnimation() {
        var container = document.createElement('div');
        container.id = 'gradio-animation';
        // 新增字体设置 ↓↓↓
        container.style.fontFamily = "'Liu Jian Mao Cao', cursive"; // 中文字体优先显示
        container.style.fontSize = '2em';
        container.style.fontWeight = 'bold';
        container.style.textAlign = 'center';
        container.style.marginBottom = '20px';

        // 在HTML头部添加字体引用（如果没有的话）
        if (!document.querySelector('#custom-font')) {
            var fontLink = document.createElement('link');
            fontLink.id = 'custom-font';
            fontLink.href = 'https://fonts.googleapis.com/css2?family=Liu+Jian+Mao+Cao&display=swap';
            fontLink.rel = 'stylesheet';
            document.head.appendChild(fontLink);
        }

        var text = '愿星辰指引你前进的方向';
        for (var i = 0; i < text.length; i++) {
            (function(i){
                setTimeout(function(){
                    var letter = document.createElement('span');
                    letter.style.opacity = '0';
                    letter.style.transition = 'opacity 0.5s';
                    letter.innerText = text[i];

                    container.appendChild(letter);

                    setTimeout(function() {
                        letter.style.opacity = '1';
                    }, 50);
                }, i * 250);
            })(i);
        }

        var gradioContainer = document.querySelector('.gradio-container');
        gradioContainer.insertBefore(container, gradioContainer.firstChild);

        const url = new URL(window.location);

        if (url.searchParams.get('__theme') !== 'dark') {
            url.searchParams.set('__theme', 'dark');
            window.location.href = url.href;
        }
    }
    """
    theme_css = '''
    margin: 0; /* 移除默认的margin */
    width: 100vw; /* 视窗宽度的100% */
    height: 100vh; /* 视窗高度的100% */
    # background-image: url('https://wallpapercave.com/wp/wp4575212.jpg'); /* 设置背景图片 */
    background-image: url('https://s3.bmp.ovh/imgs/2025/03/06/6251767d6563b93b.webp'); /* 设置背景图片 */
    background-size: cover; /* 让背景图片拉伸以填满整个元素 */
    background-position: center; /* 图片居中显示 */
    # background-repeat: no-repeat; /* 防止图片重复 */
    '''

    theme = gr.themes.Ocean().set(body_background_fill_dark = theme_css)

    # 使用Gradio Blocks创建应用
    with gr.Blocks(js=js_func, css=css, theme=theme, title="寰宇星辰") as demo:
        chat_history = gr.Chatbot(elem_classes="chatbox",
                                  height=300, show_copy_button=True,
                                  show_share_button=True,
                                  allow_tags=["thinking"],
                                  avatar_images=["../raw_data/user.png", "../raw_data/assistant.webp"],
                                  label="七月小猪AI作坊",
                                  type="messages",
                                  value=[
                                      {"role": "assistant", "content": "输入你的生日，提出你的问题，星辰将给予你答案！"}])

        with gr.Row():
            with gr.Column(scale=1):
                birthday_input = gr.Textbox(value="19970210", placeholder="请输入生日，格式yyyyMMdd", label="生日")
                model_product = gr.Textbox(visible=False, value=f"{param[1]}", label="模型供应商")
                model = gr.Textbox(visible=False, value=f"{param[2]}", label="模型")

            with gr.Column(scale=6):
                question_input = gr.Textbox(lines=2, placeholder="你的问题...", label="问题", max_length="200")
                with gr.Row():
                    clear_button = gr.Button(scale=1, value="清除历史")
                    submit_button = gr.Button(variant="primary", scale=5, value="发送(shift+enter)")

        # 使 Enter 键触发提交
        question_input.submit(anwser, [model_product, model, birthday_input, question_input, chat_history],
                              [question_input, chat_history])
        submit_button.click(anwser, [model_product, model, birthday_input, question_input, chat_history],
                            [question_input, chat_history])
        clear_button.click(clear_history, [], [chat_history])

    # 启动应用
    # demo.launch(share=True)
    demo.launch(server_name="0.0.0.0", server_port=int(param[3]))

if __name__ == "__main__":
    if len(sys.argv) > 1:
        main(sys.argv)
    else:
        print("No parameters provided.")





